package com.txt.config;



import com.txt.constant.CacheConstant;
import com.txt.listener.RedisListener;
import com.txt.listener.RedisReceiver;
import com.txt.properties.RedisProperties;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.text.MessageFormat;

@Configuration
public class RedisConfig {
    @Resource
    RedisProperties redisProperties;

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));
        return redisTemplate;
    }


    @Bean
    public MessageListenerAdapter testMessageListenerAdapter(@Qualifier("redisReceiverEvent") RedisReceiver redisReceiver ) {
        return new MessageListenerAdapter(redisReceiver, "receiveMessage");
    }

    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                                   RedisListener redisListener,
                                                   MessageListenerAdapter testMessageListenerAdapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);

        //redis key过期失效监听
        container.addMessageListener(redisListener
                , new PatternTopic(MessageFormat.format("__keyevent@{0}__:expired", redisProperties.getDatabase())));

        //redis 消息监听
        container.addMessageListener(testMessageListenerAdapter, new PatternTopic(CacheConstant.TOPIC_TEST));

        return container;
    }


}
